package com.example.container.AbortPolicy;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.RejectedExecutionException;

/**
 * AbortPolicy --- 当任务添加到线程池中被拒绝时，它将抛出 RejectedExecutionException异常。
 * Created by ZMJ on 2019/12/29.
 结果如下：
 java.util.concurrent.RejectedExecutionException: Task com.example.rejectedPolicy.AbortPolicy.MyRunnable@e9e54c2 rejected from java.util.concurrent.ThreadPoolExecutor@65ab7765[Running, pool size = 1, active threads = 1, queued tasks = 1, completed tasks = 0]
 task-0 is running.
 at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
 at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
 at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
 at com.example.rejectedPolicy.AbortPolicy.AbortPolicyDemo.main(AbortPolicyDemo.java:38)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
 task-1 is running.

 结果说明：
 将"线程池的拒绝策略"由DiscardPolicy修改为AbortPolicy之后，
 当有任务添加到线程池被拒绝时，会抛出RejectedExecutionException。

 */
public class AbortPolicyDemo {

    private static final int THREADS_SIZE = 1;
    private static final int CAPACITY = 1;

    public static void main(String[] args) throws Exception {

        // 创建线程池。线程池的"最大池大小"和"核心池大小"都为1(THREADS_SIZE)，"线程池"的阻塞队列容量为1(CAPACITY)。
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                THREADS_SIZE,
                THREADS_SIZE,
                0,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(CAPACITY)
        );

        // 设置线程池的拒绝策略为"抛出异常"
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());

        try {

            // 新建10个任务，并将它们添加到线程池中。
            for (int i = 0; i < 10; i++) {
                Runnable myrun = new MyRunnable("task-"+i);
                pool.execute(myrun);
            }
        } catch (RejectedExecutionException e) {
            e.printStackTrace();
            // 关闭线程池
            pool.shutdown();
        }
    }
}

class MyRunnable implements Runnable {
    private String name;
    public MyRunnable(String name) {
        this.name = name;
    }
    @Override
    public void run() {
        try {
            System.out.println(this.name + " is running.");
            Thread.sleep(200);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}